<template>
  <div class="feedbackPage">
    <HeaderBar title="Feed Back" @back="router.back()" />
    <div class="header_fill"></div>
    <!-- 表单 -->
    <div class="form_wrap">
      <van-form @submit="handleSubmit" ref="formRef" class="custom-form">
        <!-- 1. 邮箱输入 -->
        <div class="form-item">
          <div class="form-label required">Your email address</div>
          <van-field
            v-model="formData.email"
            name="email"
            placeholder="Email"
            class="bordered-field"
            @blur="validateEmail"
          />
          <div v-if="emailError" class="field-error">
            <img src="@/assets/images/icon_warning@2x.png" />
            <span class="text">{{ emailErrorMsg }}</span>
          </div>
        </div>

        <!-- 2. 多行文本框 -->
        <div class="form-item">
          <div class="form-label required">Description</div>
          <van-field
            v-model="formData.message"
            name="message"
            type="textarea"
            rows="3"
            autosize
            placeholder="Description"
            class="bordered-field"
            @blur="validateMessage"
          />
          <div v-if="messageError" class="field-error">
            <img src="@/assets/images/icon_warning@2x.png" />
            <span class="text">{{ messageErrorMsg }}</span>
          </div>
        </div>

        <!-- 3. 文件上传区域 -->
        <div class="form-item">
          <div class="des_text">
            Please enter the details of vour request. Amember of our support staff will respond as
            soon as possible. Please check your email。
          </div>
          <div class="form-label required">Attachments(optional)</div>
          <div class="upload-section">
            <!-- 自定义上传按钮 -->
            <div class="upload-btn" @click="triggerUpload">
              <p>
                <span style="color: #6b77ff; margin-right: 5px">Add file</span
                ><span>or drop files here</span>
              </p>
            </div>

            <!-- 隐藏的原生上传组件 -->
            <van-uploader
              ref="uploaderRef"
              v-model="fileList"
              multiple
              :max-count="10"
              :after-read="handleUpload"
              :before-delete="handleDelete"
              :before-read="beforeRead"
              class="hidden-uploader"
            />

            <!-- 图片网格展示区 -->
            <div class="image-grid">
              <div v-for="(file, index) in fileList" :key="file.name || index" class="image-item">
                <img :src="file.content || file.url" class="preview-image" />
                <img
                  src="@/assets/images/ic_close_s@2x.png"
                  class="delete-icon"
                  @click="handleDelete(index)"
                />
              </div>
            </div>
          </div>
          <!-- 错误提示 -->
          <div class="upload_error_tip" v-if="showFileError">
            <img src="@/assets/images/icon_warning@2x.png" />
            <span class="text">{{ uploadErrorText }}</span>
          </div>
        </div>

        <van-button block type="primary" native-type="submit" class="submit_btn">Submit</van-button>
      </van-form>
    </div>
    <!-- 成功弹窗 -->
    <van-popup
      v-model:show="showSuccessModal"
      round
      class="sucess_dialog"
      position="center"
      :style="{ width: '85%', maxWidth: '400px' }"
    >
      <div class="success-modal">
        <!-- 自定义成功图标 -->
        <img src="@/assets/images/ic_successfully@2x.png" class="top_img" />
        <h2 class="modal-title">Thank you for your feedback!</h2>
        <p class="modal-content">
          Our customer service team will respond within 24 hours at the latest and will contact you
          via email. Please make sure to check your inbox.
        </p>
        <div class="modal-footer">
          <van-button round block type="primary" @click="closeModal"> OK </van-button>
        </div>
      </div>
    </van-popup>
    <!-- 失败弹窗 -->
    <van-popup
      v-model:show="showFailModal"
      round
      class="sucess_dialog"
      position="center"
      :style="{ width: '85%', maxWidth: '400px' }"
    >
      <div class="success-modal">
        <!-- 自定义成功图标 -->
        <img src="@/assets/images/emoji_1@2x.png" class="top_img" />
        <h2 class="modal-title">Submission Failed</h2>
        <p class="modal-content">Check your internet connection or try again later.</p>
        <div class="modal-footer">
          <van-button round block type="primary" @click="closeFailModal"> OK </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>
<script setup>
import HeaderBar from "@/components/HeaderBar.vue";
import { ref, reactive } from "vue";
import { showToast } from "vant";
import { useRouter } from "vue-router";
import { trackEvent } from "@/utils/firebase";

const router = useRouter();

const emailError = ref(false); // 邮箱错误状态
const messageError = ref(false); // 描述错误状态
const emailErrorMsg = ref(""); // 邮箱错误信息
const messageErrorMsg = ref(""); // 描述错误信息

// 邮箱验证逻辑（失去焦点时触发）
const validateEmail = () => {
  if (!formData.email) {
    emailError.value = true;
    emailErrorMsg.value = "Email: cannot be blank";
    return false;
  }
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
    emailError.value = true;
    emailErrorMsg.value = "The email format is incorrect";
    return false;
  }
  // 验证通过时隐藏错误
  emailError.value = false;
  emailErrorMsg.value = "";
  return true;
};

// 描述验证逻辑（失去焦点时触发）
const validateMessage = () => {
  if (!formData.message) {
    messageError.value = true;
    messageErrorMsg.value = "Description: cannot be blank";
    return false;
  }
  messageError.value = false;
  messageErrorMsg.value = "";
  return true;
};

// 表单数据
const formData = reactive({
  email: "",
  message: "",
});

// 文件上传相关
const fileList = ref([]);
const showFileError = ref(false);
const uploadErrorText = ref("");
const formRef = ref(null);
const uploaderRef = ref(null);

// 邮箱格式验证函数
// const validateEmail = (val) => {
//   const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
//   return regex.test(val);
// };

// 触发文件选择
const triggerUpload = () => {
  uploaderRef.value?.chooseFile();
};

// 文件上传前校验
const beforeRead = (file) => {
  // 检查文件数量限制
  if (fileList.value.length >= 10) {
    uploadErrorText.value = "Up to 10 files can be uploaded";
    showFileError.value = true;
    return false;
  }

  // 检查文件类型
  const validTypes = ["image/jpeg", "image/png", "image/gif"];
  if (!validTypes.includes(file.type)) {
    showToast("Please upload images in JPEG/PNG format");
    return false;
  }

  // 检查文件大小 (最大5MB)
  const maxSize = 5 * 1024 * 1024;
  if (file.size > maxSize) {
    showToast("The file size cannot exceed 5MB");
    return false;
  }

  return true;
};

const handleUpload = (file) => {
  const files = Array.isArray(file) ? file : [file];
  const uniqueFiles = files.filter(
    (newFile) =>
      !fileList.value.some(
        (existingFile) =>
          existingFile.name === newFile.name &&
          existingFile.size === newFile.size
      )
  );
  fileList.value.push(
    ...uniqueFiles.map((item) => ({
      ...item,
      status: "done",
      content: URL.createObjectURL(item.file),
      id: Date.now() + Math.random(), // 生成唯一 ID
    }))
  );
  showFileError.value = false; // 隐藏错误提示
};

// 文件删除处理
const handleDelete = (index) => {
  fileList.value.splice(index, 1);
  if (fileList.value.length === 0) {
    showFileError.value = true;
    uploadErrorText.value = "You haven't selected a file yet";
  }
};

// 表单提交处理
const handleSubmit = () => {
  // 手动验证文件上传
  if (fileList.value.length === 0) {
    showFileError.value = true;
    uploadErrorText.value = "Please upload the file";
    showFailModal.value = true;
    return;
  }

  // 所有验证通过后的操作
  console.log("表单数据:", {
    ...formData,
    files: fileList.value,
  });
  // showToast("提交成功");
  showSuccessModal.value = true;
  trackEvent("【Feedback】_提交成功", { id: "100071" }); //埋点
  //trackEvent('【Feedback】_提交失败', { id: '100072'});//埋点
};
// 控制弹窗显示
const showSuccessModal = ref(false);
const showFailModal = ref(false);
// 关闭弹窗
const closeModal = () => {
  showSuccessModal.value = false;

  // 可选：关闭后重置表单
  fileList.value = [];
  formData.email = "";
  formData.message = "";
};
const closeFailModal = () => {
  showFailModal.value = false;
};
</script>

<style scoped lang="less">
.success-modal {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 32px 20px 20px 20px;
  .top_img {
    width: 80px;
  }
  .modal-title {
    font-size: 18px;
    color: rgba(0, 0, 0, 0.95);
  }
  .modal-content {
    font-size: 16px;
    color: rgba(0, 0, 0, 0.75);
    line-height: 22px;
    margin-top: 10px;
    text-align: center;
  }
  .modal-footer {
    width: 100%;
    margin-top: 20px;
    :deep(.van-button) {
      height: 51px;
    }
  }
}
.feedbackPage {
  min-height: 100vh;
  box-sizing: border-box;
  /* 背景图设置 */
  background-image: url("../assets/images/bg_texture@2x.png");
  background-position: top center; /* 从顶部开始 */
  background-repeat: no-repeat; /* 不重复 */
  background-size: 100% auto; /* 宽度满屏，高度自适应 */
  background-color: #fbfbfd;
  .header_bar {
    position: fixed;
    width: 100%;
    z-index: 999;
    background-color: #fbfbfd;
  }
  .header_fill {
    width: 100%;
    height: 56px;
  }
  .form_wrap {
    box-sizing: border-box;
    min-height: 100vh;
    background: #fff;
    // margin-top: 10px;
    padding: 12px 15px;
    border-top-left-radius: 12px;
    border-top-right-radius: 12px;
    /* 表单项容器 */
    .form-item {
      margin-bottom: 16px;
      //border-bottom: 1px solid #f5f5f5;
      //padding-bottom: 12px;
    }
    .des_text {
      font-size: 12px;
      color: rgba(0, 0, 0, 0.45);
      margin-top: 8px;
      margin-bottom: 16px;
    }

    /* 标签样式 */
    .form-label {
      margin-bottom: 8px;
      font-weight: 500;
      font-size: 16px;
      color: rgba(0, 0, 0, 0.95);
    }

    /* 必填项星号样式 */
    .form-label.required::after {
      content: "*";
      color: #f1a801;
      margin-left: 4px;
    }

    /* 带边框的输入框 */
    .bordered-field {
      border: 1px solid #ebedf0;
      border-radius: 6px;
      padding: 8px 12px;
    }

    /* 上传区域样式 */
    .upload-section {
      padding: 12px;
      border: 1px solid #ebedf0;
      border-radius: 8px;
    }

    /* 自定义上传按钮 */
    .upload-btn {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 64px;
      cursor: pointer;
      transition: all 0.3s;
      margin-bottom: 12px;
      border-radius: 4px;
      border: 1px solid rgba(0, 0, 0, 0.1);
    }

    .upload-btn span {
      margin-top: 6px;
      color: #969799;
      font-size: 12px;
    }

    /* 隐藏的上传组件 */
    .hidden-uploader {
      display: none;
    }

    /* 图片网格布局 */
    .image-grid {
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      gap: 8px;
      margin-top: 12px;
    }

    .image-item {
      position: relative;
      width: 100%;
      padding-top: 100%; /* 保持正方形 */
    }

    .preview-image {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      object-fit: cover;
      border-radius: 4px;
    }

    .delete-icon {
      position: absolute;
      top: 4px;
      right: 4px;
      width: 16px;
      color: #fff;
      z-index: 2;
      cursor: pointer;
    }

    /* 错误提示样式 */
    .error-text {
      color: #ee0a24;
      font-size: 12px;
      display: block;
      margin-top: 8px;
    }
  }
}
.field-error {
  margin-top: 4px;
  gap: 4px;
  width: 100%;
  height: 34px;
  background: rgba(255, 0, 0, 0.1);
  border-radius: 8px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  img {
    width: 16px;
  }
  .text {
    font-weight: 500;
    font-size: 12px;
    color: #ee0505;
  }
}
.bordered-field {
  margin-bottom: 4px;
}
.upload_error_tip {
  height: 34px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(255, 0, 0, 0.1);
  border-radius: 8px;
  margin-top: 8px;
  margin-bottom: 16px;
  img {
    width: 16px;
    margin-right: 10px;
  }
  .text {
    font-size: 12px;
    color: #ee0505;
  }
}
.submit_btn {
  height: 64px;
  background: linear-gradient(90deg, #89a5ff 0%, #6b77ff 100%);
  border-radius: 4px;
  border: 0;
  :deep(.van-button__text) {
    font-size: 20px;
  }
}
</style>
